package com.candy.security.jwt.weixin;

import com.candy.security.jwt.filter.CustomUsernamePasswordAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

/**
 *  配置WeixinCodeAuthenticationFilter
 *   和WeixinCodeAuthenticationProvider
 */
@Component
public class WinxinCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>
{
	@Autowired
	private AuthenticationFailureHandler authenticationFailureHandler;

	@Autowired
	private AuthenticationSuccessHandler authenticationSuccessHandler;

	@Autowired
	private UserDetailsService userDetailsService;

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public void configure(HttpSecurity http){
		WeixinCodeAuthenticationFilter smsCodeAuthenticationFilter = new WeixinCodeAuthenticationFilter(redisTemplate);
		smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
		smsCodeAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
		WeixinCodeAuthenticationProvider weixinCodeAuthenticationProvider = new WeixinCodeAuthenticationProvider(userDetailsService);
		http.authenticationProvider(weixinCodeAuthenticationProvider)
			.addFilterAfter(smsCodeAuthenticationFilter, CustomUsernamePasswordAuthenticationFilter.class);
	}
}
